import imaplib
import sys
from bs4 import BeautifulSoup
from email.parser import Parser
import getpass


server = imaplib.IMAP4_SSL(port='993', host='imap.exmail.qq.com')
print('已连接服务器')
try:
    res = server.login('alert@seedien.com','Xidian2018!!!'  )

    print('成功登陆邮箱')
except Exception as e:
    print(e)
    sys.exit(1)

server.select()
email_count = len(server.search('ALL')[1][0].split())
print("待处理邮件: %d" % email_count)

if email_count > 0:
    typ, email_content = server.fetch(f'{email_count}'.encode(), '(RFC822)')
    email_content = email_content[0][1].decode()
    # print(email_content)

    # email.parser 方法提取邮件内容
    msg = Parser().parsestr(email_content)
    print(msg)
    print("邮件类型: %s" % msg.get_content_type())
    print ("发件人: %s"% msg["From"])
    print(msg["From"].split())
    # print(msg["Cc"])
    # print(msg["To"])

    if msg["Cc"]:
      
      print("抄送邮件: %s"% msg['Cc'].split())
    else:
      print("Not CC")
  

    html = msg.get_payload(decode=True)
    # html_base64 = email_content.split("\r\n\r\n")[1]
    # html = base64.b64decode(html_base64).decode("utf-8")

    # BeautifulSoup过滤body 内容
    soup = BeautifulSoup(html, 'lxml')
    body = soup.find('div').text
    body = body.split()[0]
    print("邮件内容: %s" % body)


else:
    print('没有邮件处理')


# 根据最新id删除邮件
# server.store(str(email_count), '+FLAGS', '\\Deleted')
# server.expunge()


server.close
server.logout
print("登出邮件系统")
